﻿' ******************************************************************************
' ** 
' **  Yahoo Finance Managed
' **  Written by Marius Häusler 2010
' **  It would be pleasant, if you contact me when you are using this code.
' **  Contact: YahooFinanceManaged@gmail.com
' **  Project Home: http://code.google.com/p/yahoo-finance-managed/
' **  
' ******************************************************************************
' **  
' **  Copyright 2010 Marius Häusler
' **  
' **  Licensed under the Apache License, Version 2.0 (the "License");
' **  you may not use this file except in compliance with the License.
' **  You may obtain a copy of the License at
' **  
' **    http://www.apache.org/licenses/LICENSE-2.0
' **  
' **  Unless required by applicable law or agreed to in writing, software
' **  distributed under the License is distributed on an "AS IS" BASIS,
' **  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' **  See the License for the specific language governing permissions and
' **  limitations under the License.
' ** 
' ******************************************************************************


Friend Class MyHelper

    Public Function StreamToString(ByVal stream As IO.Stream, ByVal encoding As System.Text.Encoding) As String
        Dim res As String = String.Empty
        If stream IsNot Nothing Then
            Dim enc As System.Text.Encoding = encoding
            If enc Is Nothing Then enc = System.Text.Encoding.Default
            Using sr As New IO.StreamReader(stream, enc)
                res = sr.ReadToEnd
            End Using
        End If
        Return res
    End Function
    Public Sub CloseStream(ByVal s As IO.Stream)
        If s IsNot Nothing Then
            s.Flush()
            s.Close()
            s.Dispose()
        End If
    End Sub
    Public Function EnumToArray(Of T)(ByVal values As IEnumerable(Of T)) As T()
        If values IsNot Nothing Then
            If TypeOf values Is T() Then : Return DirectCast(values, T())
            Else : Return New List(Of T)(values).ToArray
            End If
        Else : Return New T() {}
        End If
    End Function
    Public Function CharEnumToString(ByVal arr As IEnumerable(Of Char)) As String
        Dim s As String = String.Empty
        If arr IsNot Nothing Then
            For Each c As Char In arr
                s &= c
            Next
        End If
        Return s
    End Function
    Public Function StringToObject(ByVal str As String, ByVal ci As Globalization.CultureInfo) As Object
        Dim value As String = str.Replace("%", "").Replace("""", "").Trim
        Dim dbl As Double
        If Double.TryParse(value, Globalization.NumberStyles.Any, ci, dbl) Then
            Return dbl
        Else
            Dim lng As Long
            If Long.TryParse(value, lng) Then
                Return lng
            Else
                Dim dte As Date
                If Date.TryParse(value, ci, Globalization.DateTimeStyles.AdjustToUniversal, dte) Then
                    Return dte
                Else
                    If value = "N/A" Then : Return String.Empty
                    Else : Return value
                    End If
                End If
            End If
        End If
    End Function
    Public Function ObjectToString(ByVal value As Object, ByVal ci As Globalization.CultureInfo) As String
        If value IsNot Nothing Then
            If TypeOf value Is Double Then : Return Convert.ToDouble(value).ToString(ci)
            ElseIf TypeOf value Is Date Then : Return Convert.ToDateTime(value).ToString(ci)
            Else : Return value.ToString
            End If
        Else : Return String.Empty
        End If
    End Function

    Public Function GetResultsFromXml(ByVal xml As IO.Stream, ByVal nodeName As String) As XmlNode()
        Dim res(-1) As XmlNode
        If xml IsNot Nothing AndAlso xml.CanRead Then
            Try
                Dim xmlDoc As New XmlDocument
                xmlDoc.Load(xml)
                Dim lst As XmlNodeList = xmlDoc.GetElementsByTagName(nodeName)
                Dim arr(lst.Count - 1) As XmlNode
                If lst.Count > 0 Then
                    For i As Integer = 0 To lst.Count - 1
                        arr(i) = lst(i)
                    Next
                End If
                res = arr
            Catch ex As Exception
            End Try
        End If
        Me.CloseStream(xml)
        Return res
    End Function
    Public Function GetXmlAttributeValue(ByVal node As XmlNode, ByVal attName As String) As String
        If node IsNot Nothing Then
            Dim att As XmlAttribute = node.Attributes(attName)
            If att IsNot Nothing AndAlso att.InnerText <> String.Empty Then
                Return att.InnerText
            End If
        End If
        Return String.Empty
    End Function

    Public Function YqlUrl(ByVal statement As String, Optional ByVal json As Boolean = False) As String
        Return "http://query.yahooapis.com/v1/public/yql?q=" & Uri.EscapeDataString(statement) & "&format=" & IIf(json, "json", "xml").ToString & "&diagnostics=false&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
    End Function
    Public Function YqlUrl(ByVal fields As String, ByVal table As String, ByVal whereParam As String, ByVal opt As ResultCountOptions, Optional ByVal json As Boolean = False) As String
        Return Me.YqlUrl(Me.YqlStatement(fields, table, whereParam, opt), json)
    End Function
    Public Function YqlStatement(ByVal fields As String, ByVal table As String, ByVal whereParam As String, ByVal opt As ResultCountOptions) As String
        Dim stmt As New Text.StringBuilder
        stmt.Append("select ")
        stmt.Append(fields)
        stmt.Append(" from ")
        stmt.Append(table)
        If opt IsNot Nothing AndAlso opt.Count > 0 Then
            stmt.Append("(")
            stmt.Append(opt.Start.ToString)
            stmt.Append(",")
            stmt.Append(opt.Count.ToString)
            stmt.Append(")")
        End If
        If whereParam.Trim <> String.Empty Then
            stmt.Append(" where ")
            stmt.Append(whereParam)
        End If
        Return stmt.ToString
    End Function

    Public Function CleanYqlParam(ByVal id As String) As String
        Return id.Replace("""", "").Replace("'", "").Trim
    End Function

    Public Function ServerString(ByVal server As Server) As String
        Select Case server
            Case server.Argentina : Return "ar."
            Case server.AustraliaAndNZ : Return "au."
            Case server.Brazil : Return "br."
            Case server.Canada : Return "ca."
            Case server.France : Return "fr."
            Case server.Germany : Return "de."
            Case server.HongKong : Return "hk."
            Case server.India : Return "in."
            Case server.Italy : Return "it."
            Case server.Korea : Return "kr."
            Case server.Mexico : Return "mx."
            Case server.Singapore : Return "sg."
            Case server.Spain : Return "es."
            Case server.UK : Return "uk."
            Case Else : Return String.Empty
        End Select
    End Function

    Public Function CsvTextToStringTable(ByVal csv As String, ByVal delimiter As Char) As String()()
        Dim rows() As String = csv.Split(Chr(10))
        Dim lst As New List(Of String())
        For Each row As String In rows
            If row.Trim <> String.Empty Then lst.Add(Me.CsvRowToStringArray(row.Trim, delimiter))
        Next
        Return lst.ToArray
    End Function
    Public Function CsvRowToStringArray(ByVal row As String, ByVal delimiter As Char, Optional ByVal withQuoteMarks As Boolean = True) As String()
        If withQuoteMarks Then
            Dim lstParts As New List(Of String)
            Dim actualIndex As Integer = 0
            Dim tempStartIndex As Integer = 0
            Dim waitForNextQuoteMark As Boolean = False
            Dim actualPartInQuotes As Boolean = False
            Do Until actualIndex = row.Length
                If row(actualIndex) = """" Then
                    waitForNextQuoteMark = Not waitForNextQuoteMark
                ElseIf row(actualIndex) = delimiter Then
                    If Not waitForNextQuoteMark Then
                        Dim s As String = Me.ClearCsvString(row.Substring(tempStartIndex, actualIndex - tempStartIndex))
                        lstParts.Add(s)
                        tempStartIndex = actualIndex + 1
                    End If
                End If
                actualIndex += 1
                If actualIndex = row.Length Then
                    Dim s As String = Me.ClearCsvString(row.Substring(tempStartIndex, actualIndex - tempStartIndex))
                    lstParts.Add(s)
                End If
            Loop
            Return lstParts.ToArray
        Else
            Return row.Split(delimiter)
        End If
    End Function
    Private Function ClearCsvString(ByVal csv As String) As String
        If csv.Length > 0 Then
            Dim result As String = csv
            If result.StartsWith(""""c) Then result = result.Remove(0, 1)
            If result.EndsWith(""""c) Then result = result.Remove(result.Length - 1, 1)
            Return result.Replace("""""", """"c)
        Else : Return csv
        End If
    End Function



End Class
